package com.czxy.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

//配置类
@Configuration
//要扫描的包
@ComponentScan(basePackages = {"com.czxy"})
//开启事务支持
@EnableTransactionManagement
//读取properties配置文件
@PropertySource(value = "classpath:db.properties")
public class SpringConfig {

   //4.2.4 读取properties的固定代码
   @Bean
   public static PropertySourcesPlaceholderConfigurer create(){

      return new PropertySourcesPlaceholderConfigurer();
   }
   //读取数据库中的相关配置
   @Value("${jdbc.driver}")
   private String driverClass;
   @Value("${jdbc.url}")
   private String url;
   @Value("${jdbc.username}")
   private String username;
   @Value("${jdbc.password}")
   private String password;


   //设置德鲁伊连接池
   @Bean
   public DataSource dataSource(){
      DruidDataSource dataSource = new DruidDataSource();
      dataSource.setPassword(password);
      dataSource.setUsername(username);
      dataSource.setUrl(url);
      dataSource.setDriverClassName(driverClass);
      return dataSource;
   }
   //开启事务管理器
   @Bean
   @Resource
   public DataSourceTransactionManager txManager(DataSource dataSource){
      return  new DataSourceTransactionManager(dataSource);
   }
}